package cn.ddiancan.xddcloud.common.interceptor;

import cn.ddiancan.xddcloud.common.constants.XddHeaderConstant;
import cn.ddiancan.xddcloud.common.context.XddCloudContextUtils;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

public class HeaderInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {
        // 微服务间调用，隔离了浏览器传参，对header要做整合
        String sourceService = XddCloudContextUtils.getApplication();
        String targetService = request.getURI().getHost();
        request.getHeaders().add(XddHeaderConstant.X_REQUEST_APP, sourceService);
        request.getHeaders().add(XddHeaderConstant.X_TARGET_APP, targetService);
        return execution.execute(request, body);
    }
}
